package com.zmytest.service.impl;

import com.zmytest.service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created on 2018/12/13.
 *
 * @author zhangmingyu
 */
@Service
@Slf4j
public class SessionServiceImpl implements SessionService {

    //30分钟
    private static final int EXPIRE_TIME = 1800;

    @Override
    public void create(String key,Object value) {
        HttpSession session =  getHttpSession();
        session.setAttribute(key,value);
        session.setMaxInactiveInterval(EXPIRE_TIME);
        log.info("create session key [{}], value [{}]",key,value);
    }

    @Override
    public Object get(String key) {
        return getHttpSession().getAttribute(key);
    }

    @Override
    public void delete(String key) {
        getHttpSession().removeAttribute(key);
    }

    private HttpSession getHttpSession(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest().getSession();
    }
}
